package db

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"os"
)

var Conn *gorm.DB
var db_err error

type Db struct {
	Name string
	Host string
	Port string
	User string
	Pswd string
}

func init() {
	file, open_err := os.Open("config/database.json")
	if open_err != nil {
		panic(open_err.Error())
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	db := Db{}
	//Decode从输入流读取下一个json编码值并保存在v指向的值里
	err := decoder.Decode(&db)
	if err != nil {
		panic(err.Error())
	}
	Conn, db_err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", db.User, db.Pswd, db.Host, db.Port, db.Name))
	//数据库连接字符串，端口一定要写/
	if db_err != nil { //连接成功 err一定是nil否则就是报错
		panic(db_err.Error()) //抛出异常
	}

}
